package pers.vic.boot.console.util;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/** 
 * @description: 
 * @author: Vic.xu
 * @date: 2019年11月15日 下午5:40:53
 */
public class JsonUtil {

	public static ObjectMapper objectMapper = new ObjectMapper();
	
	static {
		objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
	}
	
	
	/**
	 * 对象转JSON String
	 * @param object
	 * @return
	 */
	public static String toJson(Object object) {
		if(object == null) {
			return null;
		}
		try {
			return objectMapper.writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return null;
		}
	}
	/**
	 * 对象转JSON String 格式化的
	 * @param object
	 * @return
	 */
	public static String toJsonPretty(Object object) {
		if(object == null) {
			return null;
		}
		try {
			return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	
	public static void printJson(Object object) {
		if(object == null) {
			return;
		}
		System.out.println(object.getClass().getSimpleName() + "\n\t" +toJsonPretty(object));
	}
}
